package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.CommunityMapper;
import com.dwxt.cdms.entity.AdminUser;
import com.dwxt.cdms.entity.Community;
import com.dwxt.cdms.entity.CommunityExample;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommunityService {

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private UserServiceAdmin userServiceAdmin;

    @Autowired
    private StationService stationService;

    public BaseResult page(Page page) {
        Integer stationId = stationService.getLoginUserStation();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        CommunityExample example = new CommunityExample();
        example.setStationId(stationId);
        example.setOrderByClause("create_time desc");
        List<Community> communityList = communityMapper.selectByExample(example);
        List<Community> collect = communityList.stream().map(community -> {
            community.setStation(stationService.getStationById(community.getStationId()).getName());
            return community;
        }).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo(collect);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult list() {
        CommunityExample example = new CommunityExample();
        example.setOrderByClause("create_time desc");
        Integer stationId = stationService.getLoginUserStation();
        example.setStationId(stationId);
        List<Community> communityList = communityMapper.selectByExample(example);
        return BaseResult.ok(communityList);
    }

    public BaseResult add(Community community) {
        if (community.getStationId() == null) {
            if (Integer.valueOf(PartyUtil.getCurrentUserId())==1) {
                return BaseResult.build(StatusCode.ADMIN_CANOT_ADD_COMMUNITY);
            }
            AdminUser user = userServiceAdmin.selectUserById(Integer.valueOf(PartyUtil.getCurrentUserId()));
            String[] split = user.getStationId().split(",");
            community.setStationId(Integer.valueOf(split[0]));
        }
        communityMapper.insertSelective(community);
        return BaseResult.ok();
    }

    public BaseResult delete(Integer id) {
        communityMapper.deleteByPrimaryKey(id);
        return BaseResult.ok();
    }

    public BaseResult update(Community id) {
        communityMapper.updateByPrimaryKeySelective(id);
        return BaseResult.ok();
    }
}
